<?php
/**
* 提现
*/
class Withdraw extends CS_Controller
{
    function _init()
    {
        $this->load->helpers('common');
        $this->load->model('user_model', 'user');
        $this->load->model('withdraw_model', 'withdraw');
        $this->load->model('user_bank_model', 'user_bank');
        $this->load->model('user_account_model', 'user_account');
        $this->load->model('pay_method_model', 'pay_method');
    }

    /**
     * 提现
     */
    public function index()
    {
        $data['userBank'] = $this->user_bank->findByUid($this->uid);
        $data['userAccount'] = $this->user_account->findByUid($this->uid)->row();
        $data['payBank'] = $this->pay_method->findShortcut(2);
        $this->load->view('withdraw/index', $data);
    }

    /**
     * 插入提现数据
     */
    public function withdrawSubmit()
    {
        $postData = $this->input->post();
        if ( $postData['amount'] <= 0 || ! validateFloatNumber($postData['amount']) ) {
            $this->ajaxJson(false, '请输入有效的金额');
        }

        if (empty($postData['user_bank_id'])) {
            $this->ajaxJson(false, '请选择银行并填写银行卡号');
        }

        $bank = $this->user_bank->findById($postData['user_bank_id']);
        if ( 0 == $bank->num_rows() ) {
            $this->ajaxJson(false, '请选择银行并填写银行卡号');
        }

        $userAccount = $this->user_account->findByUid($this->uid)->row();
        if ( bccomp($userAccount->amount_carry, $postData['amount'], 2) < 0 ) {
            $this->ajaxJson(false, '提现金额超出限额');
        }

        $postData['uid'] = $this->uid;
        $postData['amount_carry'] = $userAccount->amount_carry;
        $postData['user_name'] = $this->userName;

        $withdrawId = $this->withdraw->insertWithdraw($postData, $bank->row());
        if ($withdrawId) {
            $this->ajaxJson(true, site_url('withdraw/confirm/'. $withdrawId));
        } else {
            $this->ajaxJson(false, '申请提现失败');
        }
    }

    /**
     * 确认提现信息
     */
    public function confirm($withdrawId = '')
    {
        $withdraw = $this->_isExist($withdrawId);
        if ( ! $withdraw) {
            show_404();
        }
        if (1 != $withdraw->status) {//已支付
            redirect('withdraw/progress/'. $withdraw->withdraw_id);
        }
        $data['withdrawInfo'] = $withdraw;
        $this->load->view('withdraw/confirm', $data);
    }

    /**
     * 确定提现信息
     */
    public function confirmSubmit()
    {
        $password = $this->input->post('payment_password', true);
        $withdrawId = $this->input->post('withdraw_id', true);
        $user = $this->user->findPayPassword($this->uid)->row();
//        if ( $user->payment_password != $this->_encryptPaymentPassword($password) )
//        {
//            $this->ajaxJson(false, '支付密码错误');
//        }

        if ( $user->pw != md5($password) ) {
            $this->ajaxJson(false, '支付密码错误');
        }
        $withdraw = $this->_isExist($withdrawId);
        if ( ! $withdraw) {
            $this->ajaxJson(false, '提交失败，请刷新页面重试');
        }

        $userAccount = $this->user_account->findByUid($this->uid)->row();
        if ( bccomp($userAccount->amount_carry, $withdraw->amount, 2) < 0 ) {
            $this->ajaxJson(false, '提现金额超出限额');
        }

        $this->db->trans_begin();
        $return = $this->withdraw->updatePaystatus($withdrawId, $this->uid);
        $user = $this->user_account->userWithdraw($this->uid, $withdraw->amount);

        if ( (! $return) || (! $user) || $this->db->trans_status() === FALSE ) {
            $this->db->trans_rollback();
            $this->ajaxJson(false, '申请提现失败');
        } else {
            $this->db->trans_commit();
            $this->ajaxJson(true, site_url('withdraw/confirm/'. $withdrawId));
        }
    }

    /**
     * 提现申请成功
     */
    public function progress($withdrawId = '')
    {
        $withdraw = $this->_isExist($withdrawId);
        if (!$withdraw) {
            show_404();
        }
        if (2 != $withdraw->status) { //没有支付
            redirect('withdraw/index');
        }
        $data['withdrawInfo'] = $withdraw;
        $this->load->view('withdraw/progress', $data);
    }

    public function ajaxUserBank()
    {
        $data['userBank'] = $this->user_bank->findByUid($this->uid);
        echo json_encode([
            'html'   => $this->load->view('withdraw/ajaxBankList', $data, true),
            'status' => true
        ]);
        exit;
    }

    public function ajaxInsertUserBank()
    {
        $postData = $this->input->post();
        $validResult = $this->_validateUserBank($postData);
        $validResult['uid'] = $this->uid;
        $result = $this->user_bank->insertUserBank($validResult);
        if ($result) {
            $this->ajaxUserBank();
        } else {
            $this->ajaxJson(false, '银行卡绑定失败');
        }
    }

    /**
     * 绑定银行卡信息验证
     * @param $postData
     * @return mixed
     */
    private function _validateUserBank($postData)
    {
        if ( is_int($postData['bank_id']) && $postData['bank_id'] > 0) {
            $this->_myJsonMessage('请选择银行卡类型', 'bank_id');
        }
        if ($postData['user_type'] == 1) {
            $payBank = $this->pay_method->findById($postData['bank_id']);
            if ($payBank->num_rows() == 0) {
                $this->_myJsonMessage('银行卡类型不正确', 'bank_id');
            }

            if ( ! validateBankCard($postData['bank_card']) ) {
                $this->_myJsonMessage('请填写正确的银行卡号', 'bank_card');
            }

            if ( ! validateChineseName($postData['cardholder']) ) {
                $this->_myJsonMessage('请填写正确的持卡人姓名，2个以上汉字', 'cardholder');
            }

            if ( ! validateSfz($postData['pin']) ) {
                $this->_myJsonMessage('请输入正确的身份证号码', 'pin');
            }
            $postData['bank_name']  = $payBank->row()->bank_name;
        } elseif ($postData['user_type'] == 2) {
            if ( empty($postData['company']) || strlen($postData['company']) < 4 ) {
                $this->_myJsonMessage('请输入正确的公司名称', 'company');
            }

            if ( empty($postData['bank_name']) || strlen($postData['bank_name']) < 4 ) {
                $this->_myJsonMessage('请输入正确的银行名称', 'bank_name');
            }

            if ( empty($postData['company_bank']) || strlen($postData['company_bank']) < 6 ) {
                $this->_myJsonMessage('请输入正确的对公帐号', 'company_bank');
            }
            $postData['cardholder'] = $postData['company'];
            $postData['bank_card']  = $postData['company_bank'];
        } else {
            $this->_myJsonMessage('请选择是个人还是公司', 'user_type');
        }

        if (!validateMobilePhone($postData['mobile_phone'])) {
            $this->_myJsonMessage('请输入正确的手机号码', 'mobile_phone');
        }

        if ( strlen($postData['captcha']) != 6 ) {
            $this->_myJsonMessage('短信验证码错误', 'captcha');
        }

        $endTime = date('Y-m-d H:i:s');
        $result = $this->user_code->findOne(['mobile' => $postData['mobile_phone'], 'code' => $postData['captcha']], 'id, end_time');//, 'end_time' => $endTime
        if ($result->num_rows() <= 0) {
            $this->_myJsonMessage('手机验证码错误', 'captcha');
        }
        if ($result->row(0)->end_time < $endTime) {
            $this->_myJsonMessage('手机验证码超过有效期，请重新获取~', 'captcha');
        }
        $postData['getpwd_phone_id'] = $result->row()->id;
        return $postData;
    }

    /**
     * 验证提现金额
     */
    public function ajaxAmountLimit()
    {
        $amount = $this->input->post('amount', true);
        if ($amount <= 0 || ! validateFloatNumber($amount)) {
            echo 'false';
            exit;
        }
        $result = $this->user_account->findByUid($this->uid);
        if ($result->num_rows() == 0) {
            echo 'false';
        }
        $userAccount = $result->row();
        if ( bccomp($userAccount->amount_carry, $amount, 2) <= -1) {
            echo 'false';
        } else {
            echo 'true';
        }
        exit;
    }

    /**
     * 自定义 json消息提示
     * @param $msg
     * @param string $tag
     */
    private function _myJsonMessage($msg, $tag = '')
    {
        if (empty($msg)) {
            echo json_encode(['status' => true]);
        } else {
            echo json_encode([
                'status' => false,
                'msg'    => $msg,
                'tag'    => $tag
            ]);
        }
        exit;
    }

    /**
     * 提现id是否存在
     */
    private function _isExist($withdrawId)
    {
        if ( empty($withdrawId) ) {
            return false;
        }
        $result = $this->withdraw->findById($withdrawId, $this->uid);
        if ($result->num_rows() == 0) {
            return false;
        }
        return $result->row();
    }

    /**
     * 支付密码加密
     */
    private function _encryptPaymentPassword($password)
    {
        $head = substr($password, 0, 5);
        $tail = substr($password, 5);
        return sha1(base64_encode($tail) . md5($password));
    }
}